<template>
  <div class="order-tracking">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h2>我的订单</h2>
        <p>查看当前活跃订单和处理进度</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="$router.push('/customer/create-order')">
          <el-icon><Plus /></el-icon>
          创建新订单
        </el-button>
        <el-button type="success" @click="$router.push('/customer/history')">
          <el-icon><Clock /></el-icon>
          历史记录
        </el-button>
      </div>
    </div>

    <!-- 订单状态统计 -->
    <div class="status-overview">
      <el-card 
        v-for="status in statusStats" 
        :key="status.key"
        class="status-card"
        shadow="hover"
        @click="filterByStatus(status.key)"
      >
        <div class="status-content">
          <div class="status-icon" :class="status.key">
            <el-icon size="24">
              <component :is="status.icon" />
            </el-icon>
          </div>
          <div class="status-info">
            <div class="status-count">{{ status.count }}</div>
            <div class="status-label">{{ status.label }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选和搜索 -->
    <el-card class="filter-card" shadow="never">
      <div class="filters">
        <div class="filter-group">
          <label>订单状态：</label>
          <el-select
            v-model="statusFilter"
            placeholder="全部状态"
            clearable
            style="width: 120px"
            @change="handleStatusChange"
          >
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </div>

        <div class="filter-group">
          <label>时间范围：</label>
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateRangeChange"
          />
        </div>

        <div class="filter-group">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索订单号..."
            style="width: 200px;"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <el-button type="primary" @click="resetFilters">
          <el-icon><Refresh /></el-icon>
          重置筛选
        </el-button>
      </div>
    </el-card>

    <!-- 订单列表 -->
    <div class="orders-section">
      <el-row :gutter="20">
        <el-col
          v-for="order in paginatedOrders"
          :key="order.id"
          :xs="24"
          :sm="12"
          :lg="8"
        >
          <el-card class="order-card" shadow="hover">
            <!-- 订单头部 -->
            <div class="order-header">
              <div class="order-no">{{ order.orderNo }}</div>
              <el-tag :type="getStatusType(order.status)" size="small">
                {{ getStatusText(order.status) }}
              </el-tag>
            </div>

            <!-- 订单信息 -->
            <div class="order-info">
              <div class="info-item">
                <el-icon><MapPin /></el-icon>
                <span>{{ order.stationName }}</span>
              </div>
              <div class="info-item">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatDateTime(order.createTime) }}</span>
              </div>
              <div class="info-item">
                <el-icon><Money /></el-icon>
                <span class="amount">¥{{ order.estimatedAmount || 0 }}</span>
                <span class="estimate-label">(预估)</span>
              </div>
            </div>

            <!-- 订单进度 -->
            <div class="order-progress">
              <div class="progress-header">
                <span class="progress-title">订单进度</span>
                <span class="progress-percent">{{ getProgressPercent(order.status) }}%</span>
              </div>
              <el-progress 
                :percentage="getProgressPercent(order.status)" 
                :color="getProgressColor(order.status)"
                :stroke-width="6"
                :show-text="false"
              />
              <div class="progress-desc">{{ getProgressDesc(order.status) }}</div>
            </div>

            <!-- 订单物品 -->
            <div class="order-items">
              <div class="items-summary">
                {{ order.itemsCount }}种物品，共{{ order.items.length }}项
              </div>
              <div class="items-preview">
                <el-tag
                  v-for="(item, index) in order.items.slice(0, 3)"
                  :key="index"
                  size="small"
                  type="info"
                >
                  {{ item.itemName }} {{ item.quantity }}{{ item.unit }}
                </el-tag>
                <span v-if="order.items.length > 3" class="more-items">
                  +{{ order.items.length - 3 }}...
                </span>
              </div>
            </div>

            <!-- 订单操作 -->
            <div class="order-actions">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewOrderDetail(order)"
              >
                查看详情
              </el-button>
              
              <el-button 
                v-if="order.status === 'pending'"
                type="danger" 
                size="small" 
                plain
                @click="cancelOrder(order)"
              >
                取消订单
              </el-button>
              
              <el-button 
                v-if="order.status === 'confirmed'"
                type="success" 
                size="small" 
                @click="contactStation(order)"
              >
                联系站点
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <el-empty 
        v-if="filteredOrders.length === 0" 
        description="暂无订单数据"
        :image-size="200"
      >
        <el-button type="primary" @click="$router.push('/customer/create-order')">
          创建新订单
        </el-button>
      </el-empty>
    </div>

    <!-- 分页 -->
    <div class="pagination-section" v-if="filteredOrders.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[6, 12, 18, 24]"
        :total="filteredOrders.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="orderDetailVisible"
      :title="`订单详情 - ${selectedOrder?.orderNo}`"
      width="800px"
      @close="orderDetailVisible = false"
    >
      <div v-if="selectedOrder" class="order-detail">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单号">{{ selectedOrder.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getStatusType(selectedOrder.status)">
                {{ getStatusText(selectedOrder.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="回收站点">{{ selectedOrder.stationName }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(selectedOrder.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="预约时间">{{ formatDateTime(selectedOrder.pickupTime) }}</el-descriptions-item>
            <el-descriptions-item label="取货地址">{{ selectedOrder.pickupAddress }}</el-descriptions-item>
            <el-descriptions-item label="预估金额">
              <span class="amount">¥{{ selectedOrder.estimatedAmount || 0 }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ selectedOrder.contactPhone }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 物品明细 -->
        <div class="detail-section">
          <h3>物品明细</h3>
          <el-table :data="selectedOrder.items" style="width: 100%">
            <el-table-column prop="itemName" label="物品名称" />
            <el-table-column prop="quantity" label="数量" width="100">
              <template #default="scope">
                {{ scope.row.quantity }}{{ scope.row.unit }}
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="100">
              <template #default="scope">
                ¥{{ scope.row.unitPrice }}/{{ scope.row.unit }}
              </template>
            </el-table-column>
            <el-table-column prop="subtotal" label="预估小计" width="100">
              <template #default="scope">
                <span class="amount">¥{{ scope.row.subtotal }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 订单时间线 -->
        <div class="detail-section">
          <h3>订单进度</h3>
          <el-timeline>
            <el-timeline-item
              v-for="(event, index) in selectedOrder.timeline"
              :key="index"
              :timestamp="formatDateTime(event.time)"
              :type="getTimelineType(event.status)"
            >
              <div class="timeline-content">
                <h4>{{ event.title }}</h4>
                <p>{{ event.description }}</p>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDetailVisible = false">关闭</el-button>
          <el-button 
            v-if="selectedOrder?.status === 'pending'"
            type="danger"
            @click="cancelOrderFromDetail"
          >
            取消订单
          </el-button>
          <el-button 
            v-if="selectedOrder?.status === 'confirmed'"
            type="success"
            @click="contactStationFromDetail"
          >
            联系站点
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Clock,
  Search,
  Refresh,
  MapPin,
  Calendar,
  Money,
  Document,
  Van,
  CircleCheck,
  WarningFilled
} from '@element-plus/icons-vue'
import { ordersAPI } from '@/api/orders'

// 组件名称
defineOptions({
  name: 'OrderTracking'
})

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const statusFilter = ref('')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(6)

// 对话框状态
const orderDetailVisible = ref(false)
const selectedOrder = ref(null)

// 数据
const orders = ref([])

// 状态统计
const statusStats = ref([
  { key: 'pending', label: '待确认', count: 0, icon: WarningFilled },
  { key: 'confirmed', label: '已确认', count: 0, icon: Document },
  { key: 'in_progress', label: '进行中', count: 0, icon: Van },
  { key: 'completed', label: '已完成', count: 0, icon: CircleCheck }
])

// 计算属性
const filteredOrders = computed(() => {
  let result = [...orders.value]

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(order =>
      order.orderNo.toLowerCase().includes(keyword)
    )
  }

  // 状态筛选
  if (statusFilter.value) {
    result = result.filter(order => order.status === statusFilter.value)
  }

  // 时间范围筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const [startDate, endDate] = dateRange.value
    result = result.filter(order => {
      const orderTime = new Date(order.createTime)
      return orderTime >= new Date(startDate) && orderTime <= new Date(endDate)
    })
  }

  return result.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
})

const paginatedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredOrders.value.slice(start, end)
})

// 方法
const loadOrders = async () => {
  try {
    loading.value = true
    const response = await ordersAPI.getMyOrders()
    
    console.log('📦 原始订单数据:', response)
    
    // 过滤掉已取消的订单
    const allOrders = response.data || response || []
    console.log('📦 所有订单:', allOrders)
    
    // 过滤掉已取消的订单，显示其他所有状态
    const filteredOrders = allOrders.filter(order => order.status !== 'cancelled')
    console.log('📦 过滤后的订单:', filteredOrders)
    console.log('📦 订单状态分布:', allOrders.map(o => o.status))
    
    orders.value = filteredOrders.map(order => ({
      ...order,
      // 字段映射和处理
      createTime: order.createdAt,
      contactPhone: order.customerPhone,
      estimatedAmount: order.totalAmount || 0,
      itemsCount: order.items ? [...new Set(order.items.map(item => item.itemName))].length : 0,
      items: order.items ? order.items.map(item => ({
        ...item,
        unitPrice: item.unitPrice || 0
      })) : [],
      // 生成订单进度时间线
      timeline: generateTimeline(order)
    }))
    
    console.log('📦 最终订单数据:', orders.value)
    
    // 更新状态统计
    updateStatusStats()
  } catch (error) {
    console.error('加载订单列表失败:', error)
    ElMessage.error('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

// 生成订单时间线
const generateTimeline = (order) => {
  const timeline = []
  
  // 订单创建
  if (order.createdAt) {
    timeline.push({
      time: order.createdAt,
      status: 'pending',
      title: '订单创建',
      description: '您的回收订单已成功创建，等待站点确认'
    })
  }
  
  // 根据当前状态添加相应的时间线
  if (order.status === 'confirmed' || order.status === 'in_progress' || order.status === 'completed') {
    timeline.push({
      time: order.updatedAt || order.createdAt,
      status: 'confirmed',
      title: '订单确认',
      description: '回收站已确认您的订单，将按时上门回收'
    })
  }
  
  if (order.status === 'in_progress' || order.status === 'completed') {
    timeline.push({
      time: order.actualPickupTime || order.updatedAt,
      status: 'in_progress',
      title: '开始回收',
      description: '工作人员已到达现场，正在进行回收作业'
    })
  }
  
  if (order.status === 'completed') {
    timeline.push({
      time: order.updatedAt,
      status: 'completed',
      title: '订单完成',
      description: '回收完成，款项已到账'
    })
  }
  
  if (order.status === 'cancelled') {
    timeline.push({
      time: order.updatedAt,
      status: 'cancelled',
      title: '订单取消',
      description: '订单已被取消'
    })
  }
  
  return timeline
}

const updateStatusStats = () => {
  const stats = {
    pending: 0,
    confirmed: 0,
    in_progress: 0,
    completed: 0
  }
  
  orders.value.forEach(order => {
    if (Object.prototype.hasOwnProperty.call(stats, order.status)) {
      stats[order.status]++
    }
  })
  
  statusStats.value.forEach(stat => {
    stat.count = stats[stat.key] || 0
  })
}

const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    confirmed: 'primary',
    in_progress: 'info',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待确认',
    confirmed: '已确认',
    in_progress: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || '未知'
}

const getProgressPercent = (status) => {
  const percents = {
    pending: 25,
    confirmed: 50,
    in_progress: 75,
    completed: 100,
    cancelled: 0
  }
  return percents[status] || 0
}

const getProgressColor = (status) => {
  const colors = {
    pending: '#E6A23C',
    confirmed: '#409EFF',
    in_progress: '#67C23A',
    completed: '#67C23A',
    cancelled: '#F56C6C'
  }
  return colors[status] || '#E6A23C'
}

const getProgressDesc = (status) => {
  const descs = {
    pending: '等待站点确认',
    confirmed: '已确认，等待回收',
    in_progress: '正在回收处理',
    completed: '回收完成',
    cancelled: '订单已取消'
  }
  return descs[status] || '未知状态'
}

const getTimelineType = (status) => {
  const types = {
    pending: 'warning',
    confirmed: 'primary',
    in_progress: 'info',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const formatDateTime = (dateString) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return '-'
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (e) {
    return '-'
  }
}

const filterByStatus = (status) => {
  statusFilter.value = statusFilter.value === status ? '' : status
  currentPage.value = 1
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleStatusChange = () => {
  currentPage.value = 1
}

const handleDateRangeChange = () => {
  currentPage.value = 1
}

const resetFilters = () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  dateRange.value = []
  currentPage.value = 1
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

const viewOrderDetail = (order) => {
  selectedOrder.value = order
  orderDetailVisible.value = true
}

const cancelOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个订单吗？取消后无法恢复。',
      '确认取消',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '保留订单',
        type: 'warning'
      }
    )
    
    await ordersAPI.cancelOrder(order.id, '用户主动取消')
    
    // 从列表中移除该订单（因为已取消的订单不在活跃订单列表中）
    const orderIndex = orders.value.findIndex(o => o.id === order.id)
    if (orderIndex !== -1) {
      orders.value.splice(orderIndex, 1)
    }
    
    updateStatusStats()
    ElMessage.success('订单已取消')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error(error.message || '取消订单失败')
    }
  }
}

const cancelOrderFromDetail = () => {
  if (selectedOrder.value) {
    cancelOrder(selectedOrder.value)
    orderDetailVisible.value = false
  }
}

const contactStation = (order) => {
  ElMessage.info(`正在为您转接${order.stationName}...`)
  // 这里可以实现实际的联系功能，比如打开客服对话或拨打电话
}

const contactStationFromDetail = () => {
  if (selectedOrder.value) {
    contactStation(selectedOrder.value)
  }
}

// 生命周期
onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.order-tracking {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 0;
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.status-overview {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.status-card {
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.status-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.status-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.status-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.status-icon.pending {
  background: linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%);
}

.status-icon.confirmed {
  background: linear-gradient(135deg, #409EFF 0%, #66B2FF 100%);
}

.status-icon.in_progress {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
}

.status-icon.completed {
  background: linear-gradient(135deg, #909399 0%, #B1B3B8 100%);
}

.status-info {
  flex: 1;
}

.status-count {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.status-label {
  font-size: 14px;
  color: #666;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.filters {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.orders-section {
  margin-bottom: 20px;
}

.order-card {
  margin-bottom: 16px;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.order-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.order-no {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.order-info {
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.info-item .amount {
  color: #67C23A;
  font-weight: bold;
}

.estimate-label {
  font-size: 12px;
  color: #999;
  margin-left: 4px;
}

.order-progress {
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.progress-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.progress-percent {
  font-size: 12px;
  color: #666;
}

.progress-desc {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
  text-align: center;
}

.order-items {
  margin-bottom: 16px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.items-summary {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

.items-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.more-items {
  font-size: 12px;
  color: #999;
  margin-left: 4px;
}

.order-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.order-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  border-bottom: 1px solid #e6e6e6;
  padding-bottom: 8px;
}

.detail-section .amount {
  color: #67C23A;
  font-weight: bold;
}

.timeline-content h4 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 14px;
}

.timeline-content p {
  margin: 0;
  color: #666;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .status-overview {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }
}

@media (max-width: 768px) {
  .status-overview {
    grid-template-columns: 1fr;
  }
  
  .status-content {
    justify-content: center;
    text-align: center;
  }
  
  .filters {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .filter-group {
    width: 100%;
    justify-content: space-between;
  }
  
  .header-actions {
    flex-direction: column;
    width: 100%;
  }
  
  .order-actions {
    flex-direction: column;
  }
}

/* 进度条样式优化 */
.el-progress {
  margin: 8px 0;
}

.el-progress-bar__outer {
  background-color: #e6e8eb;
  border-radius: 3px;
}

.el-progress-bar__inner {
  border-radius: 3px;
}

/* 卡片样式优化 */
.el-card {
  border: 1px solid #e6e6e6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.el-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 标签样式优化 */
.el-tag {
  border-radius: 4px;
}

/* 按钮样式优化 */
.el-button {
  border-radius: 6px;
}
</style>



